<template>
    <div>
        <div class="inputs">
            <el-input v-model="input" placeholder="请输入搜索内容" clearable />
            <el-button @click="find()" color='#E2E2E2' style="margin-left: 1vw;" type="primary">搜索</el-button>
        </div>
        <div v-if="List.length != 0" class="infinite-list-wrapper" style="">
            <el-scrollbar class="list" height="100%">
                <div @click="friend(i.userId, i.name, index)" 
                @click.right="rightClick(i.userId,i.topStatus,index,$event)" 
                v-for="i, index in List" :key="i.userId"
                    :class="{ 'list-item': true, 'activ': index == activ, 'topStatus': i.topStatus }">
                    <el-badge :value="classify[i.userId]" :hidden="!classify[i.userId]" class="item">
                        <img :src="i.imageUrl" alt="">
                    </el-badge>

                    <div class="name">
                        <div>
                            <div class="userName">{{ i.name }}</div>
                            <div class="time">{{ i.sendTime ? time(new Date(i.sendTime), false) : time(new Date(), false) }}
                            </div>
                        </div>
                        <div>{{ i.content }}</div>
                    </div>
                </div>
                <p v-if="loading">Loading...</p>

            </el-scrollbar>

        </div>
        <div class="infinite-list-wrapper" v-else style="flex: 1;">
            没有聊天好友，搜索好友开始聊天吧
        </div>
        <teleport to="body">
            <el-dialog class="dialogs" v-model="dialogVisible" title="搜索用户" width="30%">
                <el-scrollbar height="300px">
                    <div v-for="item in findList" class="finduser">
                        <div class="ac">
                            <img :src="item.imageUrl" alt="">
                            <div>{{ item.name }}</div>
                        </div>
                        <div class="zt ac" @click="seek(item)">找他聊天</div>
                    </div>
                </el-scrollbar>
                <el-pagination class="pagination" background layout="prev, pager, next" @current-change="currentChange"
                    :total="pageCount * 10" />
            </el-dialog>
        </teleport>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, inject, watch } from "vue"
import { friends, findUser ,topUser,cancelTopUser} from '@/request/api'
import { useWebSocket } from '@/hooks/index'
import type { List, Response, findList } from '@/type/friend'
import { time } from '@/hooks/index'
import { useStore } from '@/stores/counter'
import { Ls } from "dayjs"

const store = useStore()
const loading = ref(false)      //loading

//鼠标右键用户列表
const rightClick=(id:string,topStatus:number,index:number,e:any)=>{
    let mark=List[index]
    if(!topStatus){
        topUser<string>(id).then(res=>{
            List[index].topStatus=1
            List.splice(index,1)
            List.unshift(mark)
            activ.value==index?activ.value=0:     activ.value+=1
       
        })
    }else{
        cancelTopUser<string>(id).then(res=>{
            List[index].topStatus=0
            List.splice(index,1)
            List.push(mark)
            activ.value==index?activ.value=List.length-1:     activ.value-=1
        })
    }
    e.preventDefault();

}

let input = ref<string>('')//搜索值
// let pageIndex = ref(1)      //当前好友分页的页数
let List = reactive<List[]>([])     //好友列表      
interface friends {
    keyword?: string;
    pageIndex?: number;
    pageSize?: number;
}
friends<friends>({

}).then(res => {
    List.push(...res.data)
    res.data.forEach(e => {
        classify[e.userId] = e.unreadRecords
    })
    if (List.length != 0)
        friend(List[0].userId, List[0].name, 0)
})

//开始聊天
let activ = ref(0)
const emit = defineEmits(['on_click'])
const friend = (id: string, name: string, index: number) => {
    emit("on_click", { id, name })
    activ.value = index
    classify[id] = 0
}


//接收聊天通知
let classify: any = reactive({})        //用于格式化，查看哪些好友的消息未读
const message = (e: Response) => {

    if (e instanceof Array) return       //判断是不是第一次的通知，第一次是数组
    if (e.type != "NEWS") return            //判断是不是聊天消息通知
    //判断这次消息是不是用户发送的消息
    if ((e.sendUserId as number) == store.user.id) {
        List[activ.value].sendTime = e.sendTime as string
        List[activ.value].content = e.content
        seek(List[activ.value])
    } else {

        let index = -1
        let item: List | null = null
        List.forEach((element, i) => {
            if (element.userId == e.sendUserId) {
                List[i].content = e.content
                List[i].sendTime = e.sendTime as string
                item = List[i]
                index = i
            }
        })
        index != -1 ? List.splice(index, 1) : ""
        //判断是否是好友列表里面来的信息
        item ? '' : item = {
            userId: e.sendUserId as string,
            imageUrl: e.sendUserImageUrl,
            content: e.content,
            topStatus: 0,
            sendTime: e.sendTime as string,
            name: e.sendUserName,
            unreadRecords: 1,
            readStatus: 0


        }
        //获取置顶最后的一个下标
        let topStatus = -1
        List.forEach(e => {
            e.topStatus ? topStatus++ : ''
        })
        topStatus > -1 ? List.splice(topStatus + 1, 0, item) : List.unshift(item)
        List[activ.value].userId != e.sendUserId ? classify[e.sendUserId]++ : classify[e.sendUserId] = 0
    }



}
//开始格式化
const census = (arr: Response[]) => {
    arr.forEach((elemnt) => {
        if (elemnt.sendUserId in classify) {
            classify[elemnt.sendUserId]++
        } else {
            classify[elemnt.sendUserId] = 1
        }

    })


}
//第一次先取到值
let friendsArr: Response[] = inject('friendsArr') as Response[]

watch(friendsArr, () => {
    census(friendsArr)
})
let ws = useWebSocket('friend', message)

interface Find {
    /**
     * 关键词，可输入id或name进行模糊匹配
     */
    keyword?: string;
    /**
     * 页码
     */
    pageIndex?: number;
    /**
     * 页大小
     */
    pageSize?: number;
}

//搜索好友
let indexs = 0
//获取搜索的好友
const find = () => {
    dialogVisible.value = true
    findUser<Find>({
        keyword: input.value,
        pageSize: 10,
        pageIndex: indexs
    }).then(res => {
        findList.length = 0
        findList.push(...res.data.list)
        pageCount.value = res.data.pageCount
    })
}
//搜索出来的用户列表
let findList = reactive<findList[]>([])
let pageCount = ref(0)
let dialogVisible = ref(false)
//搜索好友分页
const currentChange = (e: number) => {
    indexs = e
    find()
}
const seek = (item: any) => {
    let index = Math.max(...List.map((e, index) => {
        if (e.userId == item.userId)
            return index
        return -1
    }))
    console.log(index);
    
    let topStatus = -1
    if(index!=-1)
    List.splice(index, 1)
    List.forEach(e => {
        e.topStatus ? topStatus++ : ''
    })
    topStatus > -1 ? List.splice(topStatus + 1, 0, item) : List.unshift(item)
    friend(item.userId, item.name, topStatus + 1)
    dialogVisible.value = false
}
</script>

<style lang=less  scoped>
.inputs {
    display: flex;
    // height: 20vh;
    justify-content: space-between;
    margin-bottom: 2vh;
    padding-right: 1vw;
}

.infinite-list-wrapper {
    position: relative;
    flex: 1;
    text-align: center;

}

.infinite-list-wrapper .list {
    padding: 0;
    width: 100%;
    margin: 0;
    background-color: @backColor;
    color: @color;
    list-style: none;
    position: absolute;
}

.infinite-list-wrapper .list-item {
    display: flex;
    align-items: center;
    padding: 10px;
    height: 50px;

    cursor: pointer;
}

.list-item:hover {

    .activ();
}

:deep(.el-input__wrapper) {

    background-color: #e2e2e2bb;
}

img {
    width: 50px;
    aspect-ratio: 1/1;
}

.name {
    height: 100%;
    flex: 1;
    position: relative;
    text-align: left;
    margin-left: 0.5vw;
    font-size: 0.8vw;

    .userName {
        flex: 1;
        .textNOLine();
    }

    // flex-wrap: wrap;
    // display: flex;
    // align-content: space-between;
    >div {
        width: 100%;
        position: absolute;

        .time {
            font-size: 0.7vw;
            color: #99999986;
        }
    }

    >div:nth-child(1) {
        display: flex;
        justify-content: space-between;
    }

    >div:nth-child(2) {
        font-size: 0.7vw;
        color: #999999;
        .textNOLine();
        position: absolute;
        bottom: 0px;
    }
}

.activ {
    background-color: #c6c6c65e !important;
}

.dialogs {
    .finduser {
        margin: 5px 0px;
        padding-bottom: 2px;
        cursor: pointer;
        width: 100%;
        .flexAc();
        height: 40px;
        justify-content: space-between;

        border-bottom: 1px solid #b8b8b88c;

        img {
            width: 30px;
            aspect-ratio: 1/1;
            border-radius: 50%;
        }

        .ac {
            .flexAc();
            margin: 0px 5px;
        }

        .zt {
            opacity: 0;
            display: inline-block;
        }


    }
}

.finduser:hover {
    background-color: #f1eeee86;
}

.finduser:hover .zt {
    opacity: 1;
}

.zt::after {
    content: ' ';
    display: block;
    height: 1px;
    background-color: #606266;
    transition: all 0.3s ease-in-out;
    transform: scale(0);
    transform-origin: left;

}

.zt:hover::after {
    transform: scale(1);
}

.topStatus {
    background-color: #eeeeeee1;
}
</style>